<?php

namespace Api\Event;


/** 
 * 赛事接口
 * @author Legend. <xcx_legender@qq.com>
 * @param 
 * @return 
 */

class MatchEvent extends BaseEvent {

	protected $mod;

	protected function _initialize(){
		parent::_initialize();
		$this->mod = D('Common/Match', 'Service');
	}

	// 获取单条赛事信息
	public function info($id = 0)
	{
		return $this->mod->find($id);
	}

	// 获取赛事及相关的全部信息
	public function detail($id = 0)
	{
		$match = $this->info($id);
		if ($match && $match['game_id'])
		{
			$mod_game = A('Api/Game', 'Event');
			$match['game'] = $mod_game->info($match['game_id']);
		}
		return $match;
	}

	// 获取赛事的key:value信息
	public function options($game_id = 0)
	{
		$matches = $this->lists($game_id);
		foreach ($matches as $key => $value) {
			$data[$value['id']] = $value['title'];
		}
		return $data;
	}

	/**
	*赛事总数
	*@param array $filter 过滤条件
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function total($filter=array()){

		$serObj = D('Common/Match', 'Service');
		$map = array(
				'status'=>$serObj::STATUS_PASS
			);
		if($filter)
			$map = array_merge($map, $filter);

		return $serObj->where($map)->count();
		
	}

	/**
	*某一赛事下的比赛总数
	*@param array $filter 过滤条件
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function raceTotal($filter=array()){

		$serObj = D('Common/Video', 'Service');
		$map = array(
				'status'=>$serObj::STATUS_PASS,
				'type'=>$serObj::TYPE_MATCH
			);
		if($filter)
			$map = array_merge($map, $filter);

		return $serObj->where($map)->count();
		
	}

	/**
	*根据筛选条件获取赛事列表
	*@param array $filter 过滤条件
	*@param int $limit 返回的条数
	*@return array 资源数据
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	// 添加$game_id参数  by liubo<liubo@ilongyuan.com.cn> at 2016-07-06
	public function lists($p=1, $limit=20, $showGame=true, $field='', $game_id = 0){

		$serObj = D('Common/Match', 'Service');	

    	$map = array(
				'status'=>$serObj::STATUS_PASS
			);
    	if (!empty($game_id)) {
    		$map['game_id'] = is_array($game_id) ? ['$in' => $game_id] : intval($game_id);
    	}
    	$orderby = 'sort desc, match_state desc, create_time desc';
    	$resource = $serObj->where($map)->field($field)->page($p)->limit($limit)->order($orderby)->select();

		$gEvent = A('Api/Game', 'Event');
		foreach ($resource as $key => $value) {
			if($showGame){
				$game = $gEvent->info($value['game_id']);
				uri_format($game['pic']);
				uri_format($game['logo']);
				uri_format($game['background']);
				$resource[$key]['game'] = $game;
			}
			
		}
    	return $resource;
    }

    /**
    *针对于游戏，获取赛事列表
    *@param int $gid 游戏标识
    *@param int $timestamp 范围时间戳
    *@param  int $limit 列表个数
    *@param string $field 信息项
    *@return array()
    *@author susy.liang<liangling@ilongyuan.com.cn>
    */
    public function gameMatches($gid, $timestamp=0, $limit=20, $field=''){

    	$serObj = D('Common/Match', 'Service');	

    	$map = array(
				'status'=>$serObj::STATUS_PASS,
				'game_id'=>$gid
			);
    	$timestamp && $map['create_time'] = array('lt', $timestamp);
    	$orderby = 'create_time desc';
    	$resource = $serObj->where($map)->field($field)->limit($limit)->order($orderby)->select();
    	
		$gEvent = A('Api/Game', 'Event');
		foreach ($resource as $key => $value) {
				$game = $gEvent->info($value['game_id']);
				uri_format($game['pic']);
				uri_format($game['background']);
				$resource[$key]['game'] = $game;
			
		}

    	return $resource;

    }

    /**
    *获取赛事下的最近的赛程
    *@param int $matchId 赛事ID
    *@author susy<susy.liang@ilongyuan.com.cn>
    */
    public function getLatest($matchId){

    	$servVideo = D('Common/Video', 'Service');

    	$map = array(
				'type'=>$servVideo::TYPE_MATCH,
				'status'=>$servVideo::STATUS_PASS,
				'match_id'=>$matchId
				);
    	$res = $servVideo->where($map)->field('match_time')->order('match_time desc')->limit(1)->select();
    	$res = array_pop($res);
    	return $res?$res['match_time']:'';

    }

    /**
    *获取赛事下的默认比赛的日期
    *当天有比赛的则取当天时间，反之取最新的时间
    *@param int $matchId 赛事id
    *@author susy.liang<susy.liang@ilongyuan.com.cn>
    */
    public function getDefDate($matchId){

    	$servVideo = D('Common/Video', 'Service');

    	$nowtime = strtotime(date('Y-m-d', time()));
    	$map = array(
    			'type'=>$servVideo::TYPE_MATCH,
				'status'=>$servVideo::STATUS_PASS,
				'match_id'=>$matchId,
    		);
    	$res = $servVideo->where($map)->order('match_time desc')->getField('match_time', true);
    	if(in_array($nowtime, $res))
    		return $nowtime;
    	else
    		return $res[0];

    }

   /**
	*获取赛事下的比赛信息
	*@param array $filetr过滤条件
	*@param int $page 当前页数
	*@param int $limit 列表数限制
	*@param string $orderby 排序条件
	*@param string $field 获取的字段项
	*@param boolean $timeShow 是否获取战队信息 true|获取 false|否
	*@param string $defTeamLogo 默认的战队logo 来源于赛事设置的战队logo
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	//这是旧版的赛事比赛接口
	public function races($filter=array(), $page=0 ,$limit=0, $orderby="id desc", $field='', $teamShow=true, $defTeamLogo=''){
		
		$servVideo = D('Common/Video', 'Service');

		$map = array(
				'type'=>$servVideo::TYPE_MATCH,
				'status'=>$servVideo::STATUS_PASS
				);
		if($filter)
			$map = array_merge($map, (array)$filter);

		$res = $servVideo->where($map)->page($page);
		if($page)
			$res = $res->page($page);
		if($limit)
			$res = $res->limit($limit);
		$data = $res->field($field)->order($orderby)->select();

		if($data && $teamShow){
			//start modify by susy.liang at  2015/8/10 比赛结构调整，故需要修改获取战队的信息获取
			/*$teamEvent = A('Api/Team', 'Event');
			$field = 'id,name,logo,full_name';
			$tmpTeam = array();
			foreach ($data as $key => $value) {
				$teams = $value['competitor'];
				foreach ($teams as $k => $val) {
					$tmpTeam = $teamEvent->infoByName($val, $field);
					$team[$k] = array(
							'name'=>$tmpTeam['full_name'],
							'shortName'=>$tmpTeam['name'],
							'logo'=>$tmpTeam['logo']?$tmpTeam['logo']:$defTeamLogo
						);
				}
				$data[$key]['team'] = $team;
				unset($data[$key]['competitor']);
				
				$score = array_map('intval', explode('-', $value['score']));
				$scorePoint = array_map('intval', explode('-', $value['score_point']));
				$data[$key]['score'] = $score?$score:array(0,0);
				$data[$key]['score_point'] = $scorePoint?$scorePoint:array(0,0);
			}*/

			$grpObj = A('Api/RaceGroup', 'Event');

			foreach ($data as $key => $value) {
				$raceGrp = $grpObj->info(intval($value['group_id']), $defTeamLogo);
				$data[$key]['team'] = $raceGrp['team'];
				
				$score = array_map('intval', explode('-', $raceGrp['score']));
				$scorePoint = array_map('intval', explode('-', $value['score']));

				$data[$key]['score'] = $score?$score:array(0,0);
				$data[$key]['score_point'] = $scorePoint?$scorePoint:array(0,0);
			}

		}

		//end

		return $data;

	}

	/**
	*获取比赛下的视频
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function videoOld($id, $uid){

		$eventTeam 	= A('Api/Team', 'Event');
		$eventVideo = A('Api/Video', 'Event');
		$servVideo = D('Common/Video', 'Service');

		$raceMap = array(
					'id'=>$id,
					'type'=>$servVideo::TYPE_MATCH,
					'status'=>$servVideo::STATUS_PASS
			);
		$race = $servVideo->where($raceMap)->find();


		if($race){

			$game = A('Api/Game', 'Event')->info($race['game_id']);
			uri_format($game['pic']);
			$race['game'] = $game;
			
			uri_format($race['thumb']);
			$race['score'] = $race['score']?array_map('intval', explode('-', $race['score'])):array();
			$race['score_point'] = $race['score_point']?array_map('intval', explode('-', $race['score_point'])):array();
			
			//start 比赛视频信息结构调整 susy.liang
			//$timeGrp = preg_split('/[,;\r\n]+/', trim($race['time_group'], ",;\r\n"));
			//$videoIds = $race['videos'];
			$timeGrp = $race['match_times'];
			$videoIds = $race['match_videos'];
			//end
			$videoData = array();
			if($videoIds){
				foreach ($videoIds as $key => $value) {
					$videos = $eventVideo->detail($value, $uid, false);
					if($videos){
						$eventVideo->setPlay($value);
						$videos['time_point'] = $timeGrp[$key];
						$videoData[] = $videos;
					}					
				}
			}
			$race['videos'] = $videoData;
			
			//战队信息的获取 
			/*$teamData = array();
			$teams = $race['competitor'];
			if($teams){

				$defLogo = $this->mod->field('teamlogo')->find(intval($race['match_id']));
				$defLogo = $defLogo['teamlogo'];
				uri_format($defLogo);

				$tmpTeam = array();
				$field = 'id,name,full_name,logo';
				foreach ($teams as $key => $value) {
					$tmpTeam = $eventTeam->infoByName($value, $field);
					$teamData[$key] = array(
							'name'=>$tmpTeam['full_name'],
							'shortName'=>$tmpTeam['name'],
							'logo'=>$tmpTeam['logo']?$tmpTeam['logo']:$defLogo
						);
				}
			}
			$race['teams'] = $teamData;*/
			$teamLogo = D('Common/Match', 'Service')->field('teamlogo')->find(intval($race['match_id']));
			$teamLogo = $teamLogo['teamlogo'];
			uri_format($teamLogo);

			$raceGroup = A('Api/RaceGroup', 'Event')->info($race['group_id'], $teamLogo);
			$race['group_title'] = $raceGroup['title'];
			$race['teams'] = $raceGroup['team'];
			//end

			$eventVideo->setPlay($id);//加入播放次数 at 2015/7/3 by susy<susy.liang@ilongyuan.com.cn>
		}

		return $race;
	}

	/**
	*获取比赛下的视频
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function video($id, $uid){

		$eventTeam 	= A('Api/Team', 'Event');
		$eventVideo = A('Api/Video', 'Event');
		$servVideo = D('Common/Video', 'Service');

		$raceMap = array(
					'id'=>$id,
					'type'=>$servVideo::TYPE_MATCH,
					'status'=>$servVideo::STATUS_PASS
			);
		$race = $servVideo->where($raceMap)->find();
		if($race){

			$game = A('Api/Game', 'Event')->info($race['game_id']);
			uri_format($game['pic']);
			$race['game'] = $game;
			
			uri_format($race['thumb']);
			$race['score'] = $race['score']?array_map('intval', explode('-', $race['score'])):array();
			//$race['score_point'] = array_map('intval', explode('-', $race['score_point']));
			
			$videoData = array();
			$timeGrp = $race['match_times'];
			$videoIds = $race['match_videos'];
			if($videoIds){
				foreach ($videoIds as $key => $value) {
					$videos = $eventVideo->detail($value, $uid, false);
					if($videos){
						// $eventVideo->setPlay($value);
						$videos['time_point'] = $timeGrp[$key];
						$videoData[] = $videos;
					}					
				}
			}
			$race['videos'] = $videoData;
			
			//start team 
			$teamLogo = D('Common/Match', 'Service')->field('teamlogo')->find(intval($race['match_id']));
			$teamLogo = $teamLogo['teamlogo'];
			uri_format($teamLogo);

			$raceGroup = A('Api/RaceGroup', 'Event')->info($race['group_id'], $teamLogo);
			$race['group_title'] = $raceGroup['title'];
			$race['team'] = $raceGroup['team'];
			$race['race_date'] = $raceGroup['race_date'];
			$race['race_hour'] = $raceGroup['race_hour'];
			foreach ($race['team'] as $key => &$val) {
				if($val['shortName'] == $race['winner'])
					$val['is_winner'] = 1;
				else
					$val['is_winner'] = 0;
			}
			$race['total_score'] = $raceGroup['score']?array_map('intval', explode('-', $raceGroup['score'])):array();;
			//end

			// $eventVideo->setPlay($id);//加入播放次数 at 2015/7/3 by susy<susy.liang@ilongyuan.com.cn>
			
			$cacheEvent = event('Cache');
			$res = $cacheEvent->videoStatis($id,'get');
			if (!$res)
			{
				# 
				# 读取原数据 然后加入到新表 然后存储到缓存里
				# 
				$res = service('StatisAll')->getVideoStatis($id);
				$cacheEvent->videoStatis($id,'set','', $res);
			}
			$race['comments'] = $res['comments'] ?: 0;

		}
		// print_r($race);
		return $race;
	}


	/**
	*获取赛事的赛时安排
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function matchDate($id, $limit=0, $totext=true){

		$servVideo = D('Common/Video', 'Service');

		$map = array(
				'match_id'=>$id,
				'type'=>$servVideo::TYPE_MATCH,
				'status'=>$servVideo::STATUS_PASS
			);
		$res = $servVideo->where($map)->field('match_time')->order('match_time desc');
		//个数限制改为数组array_chunk,因为mongo无法去重复查询 susy.liang
		/*if($limit)
			$res = $res->limit($limit);*/
		//end
		$dates = $res->select();
		
		if(!$dates)
			return false;

		$data = array();
		$temp = array();
		foreach ($dates as $key => $value) {
			if(!in_array($value['match_time'], $temp)){
				$temp[] = $value['match_time'];
				if($totext){
					$strText = $this->dateToStr(date("D", $value['match_time']));
					$data[] = array('date'=>date('Y-m-d', $value['match_time']), 'str_text'=>$strText);
				}else{
					$dk = date('Y年m月', $value['match_time']);
					$data[$dk][] = array(
									'date'=>date('m-d', $value['match_time']),
									'unixtime'=>date('Y-m-d', $value['match_time'])
									);
				}
				
			}
		}

		if($limit){
			$data = array_chunk($data, $limit);
			$data = $data[0];
		}

		return $data;
	}


	/**
	*日期和周几的转换
	*/
	private function dateToStr($date){
		switch   ($date){ 
	        case   "Mon": 
				$current   =  "星期一"; //"星期一 MONDAY"; 
				break; 
	        case   "Tue": 
				$current   =  "星期二 ";// "星期二 TUESDAY"; 
				break; 
	        case   "Wed": 
				$current   =   "星期三";//"星期三 WEDNESDAY"; 
				break; 
	        case   "Thu": 
				$current   =   "星期四";//"星期四 THURSDAY"; 
				break; 
	        case   "Fri": 
				$current   =   "星期五";//"星期五 FRIDAY"; 
				break; 
	        case   "Sat": 
				$current   =   "星期六";//"星期六 SATURDAY"; 
				break; 
	        case   "Sun": 
				$current   =   "星期日";//"星期日 SUNDAY"; 
				break; 
		}
		return $current;
	}

	/**
	*获取默认的比赛列表
	*先根据赛事的直播/预告/普通状态 筛选符合的赛事
	*然后取赛事下最近的时间的比赛各一条
	*---------------------------------------------
	*@param int $limit 限制个数
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*/
	public function getDefRaces($limit=3){

		$matches = $this->lists(0, $limit, false);
		if($matches){

			$vdServ = D('Common/Video', 'Service');
			$teamEvent = A('Api/Team', 'Event');

			$data = array();
			$curhour = date('H:i', time());
			$curDate = strtotime(date('Y-m-d', time()));
			$fieldMap = array('id', 'title', 'subtitle', 'teamlogo', 'match_state','race');
			foreach ($matches as $key => $value) {
				//取比赛
				$filter = array(
						'match_id'=>intval($value['id']),
						'status'=>$vdServ::STATUS_PASS
					);
				if($value['match_state'] == 2){
					$filter['match_time'] = $curDate;
					$filter['match_hour'] = array('elt', $curhour);
					
				}
				$races = $vdServ->where($filter)->order('match_date asc,match_hour asc')
						->field('id,match_time,match_hour,competitor,score,score_point,group_id')->select();

				if($races){
					$races = array_pop($races);
					unset($races['_id']);

					$races['title'] = $value['title'];
					//start modify by susy.liang at  2015/8/10 后台比赛重构，须重取战队，比分信息
					/*$teams = $races['competitor'];
					if($teams){
						foreach ($teams as $k => $val) {
							$tmpTeam = $teamEvent->infoByName($val);
							$team[$k] = array(
									'name'=>$tmpTeam['full_name'],
									'shortName'=>$tmpTeam['name'],
									'logo'=>$tmpTeam['logo']?$tmpTeam['logo']:$defTeamLogo
								);
						}
						$races['team'] = $team;

						unset($races['competitor']);
					}

					$score = array_map('intval', explode('-', $races['score']));
					$scorePoint = array_map('intval', explode('-', $races['score_point']));
					$races['score'] = $score?$score:array(0,0);
					$races['score_point'] = $scorePoint?$scorePoint:array(0,0);*/
					uri_format($value['teamlogo']);
					$racegrp = A('Api/RaceGroup', 'Event')->info(intval($races['group_id']), $value['teamlogo']);
					$races['team'] = $racegrp['team'];
					$score = array_map('intval', explode('-', $racegrp['score']));
					$scorePoint = array_map('intval', explode('-', $races['score']));

					$races['score'] = $score?$score:array(0,0);
					$races['score_point'] = $scorePoint?$scorePoint:array(0,0);

					unset($races['competitor']);
					//end
					$value['race'] = $races;
				}else{
					unset($matches[$key]);
				}
				
				$data[] = field_filter($value, $fieldMap);
			}
		}
		return $data;
	}

	/**
	 * 获取赛事游戏列表
	 * @author liubo <liubo@ilongyuan.com.cn>
	 */
	public function games()
	{
		$serObj = D('Common/Match', 'Service');	

    	$map = array(
			'status'=>$serObj::STATUS_PASS
		);
    	$ids = $serObj->where($map)->getField('game_id', true);
    	array_unique($ids);
    	$map = [
    		'id' => ['$in' => $ids],
    	];
    	$games = event('game')->lists($map, 'id,name,logo');
    	foreach ($games as &$value) {
    		uri_format($value['logo']);
    	}
    	return array_values($games);
	}
}